<template>
  <div>
    
     <!-- 面包屑导航区 -->
         <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
          <!-- 消息提示 -->
          
            <el-alert title="消息提示的文案" type="info" show-icon center :closable="false"></el-alert>
            <!-- 步骤条 -->
            <el-steps  :space="200" :active="+selectActive" finish-status="success" align-center>
              <el-step title="基本信息"></el-step>
              <el-step title="商品参数"></el-step>
              <el-step title="商品属性"></el-step>
              <el-step title="商品图片"></el-step>
              <el-step title="商品内容"></el-step>
              <el-step title="完成"></el-step>
            </el-steps>
            <!-- 标签页 -->
         <el-form :model="addForm" :rules="addRules" ref="adRruleForm" label-width="100px" label-position='top' >   
            <el-tabs v-model="selectActive" :tab-position="tabPosition" :before-leave ='changeTab' @tab-click='qiehuan'>
              <el-tab-pane name="0" label="基本信息">
                  <el-form-item label="商品名称" prop="goods_name">
                    <el-input v-model="addForm.goods_name"></el-input>
                  </el-form-item>
                  <el-form-item label="商品价格" prop="goods_price">
                    <el-input v-model="addForm.goods_price" type="number"></el-input>
                  </el-form-item>
                  <el-form-item label="商品重量" prop="goods_weight">
                    <el-input v-model="addForm.goods_weight" type="number"></el-input>
                  </el-form-item>
                  <el-form-item label="商品数量" prop="goods_number">
                    <el-input v-model="addForm.goods_number" type="number"></el-input>
                  </el-form-item>
                  <el-form-item label="商品分类"  prop="goods_cat" >
                  <el-cascader
                        v-model="addForm.goods_cat"
                        :options="goodCateList"
                        :props="cascaderProps"
                        @change="handleChange"
                        clearable
                        >
                  </el-cascader>
                  </el-form-item>
              </el-tab-pane>
              <el-tab-pane name="1" label="商品参数">
                 <el-form-item :label="item.attr_name" v-for="item in manyTabList" :key="item.attr_id">
                        <el-checkbox-group v-model="item.attr_vals">
                          <el-checkbox :label="v" v-for="(v,i) in item.attr_vals" :key="i"></el-checkbox>
                        </el-checkbox-group>
                 </el-form-item>
              </el-tab-pane>
              <el-tab-pane name="2" label="商品属性">
                 <el-form-item :label="item.attr_name" v-for="item in onlyTabList" :key="item.attr_id">
                      <el-input v-model="item.attr_vals" ></el-input>
                 </el-form-item>
              </el-tab-pane>
              <el-tab-pane name="3" label="商品图片">
                 <el-upload
                        class="upload-demo"
                        :action="upLoadUrl"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        :file-list="fileList"
                        :headers ='headersObj'
                        :on-success ='handleSuccess'
                        list-type="picture">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                      </el-upload>
              </el-tab-pane>
              <el-tab-pane name="4" label="商品内容">
                <quill-editor v-model="addForm.goods_introduce">
                   
                </quill-editor>
                <el-button class="btn" type="primary" @click="add">添加商品</el-button>
              </el-tab-pane>
            </el-tabs>
         </el-form>
        </el-card>
        <el-dialog
          title="图片预览"
          :visible.sync="dialogVisible">
          <img :src="trueFiles" alt="">
        </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name:'addIndex',
  components: {},
  props: {},
  computed:{
    fenId(){
      return this.addForm.goods_cat[2]
    }
  },
  data() {
    return {
      selectActive:'0',
       tabPosition: 'left',
      //  表单的数据配置
      addForm:{
        goods_name:'',
        goods_price:1,
        goods_weight:0,
        goods_number:0,
        goods_cat:[],
        pics:[],
        goods_introduce:'',
        attrs:[]
      },
      addRules:{
        goods_name:[{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price:[{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight:[{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number:[{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat:[{ required: true, message: '请输入商品数量', trigger: 'blur' }]
         
      },
      // 级联选择器的数据
       goodCateList:[],
      cascaderProps:{
        expandTrigger: 'hover',
        value:'cat_id',
        label:'cat_name',
        children:'children',
        checkStrictly: true
      },
      manyTabList:[],
      onlyTabList:[],
      //上传组件配置
      upLoadUrl:"http://127.0.0.1:8888/api/private/v1/upload",
      headersObj:{
         Authorization:window.sessionStorage.getItem('token')
      },
      trueFiles:'',
      dialogVisible:false,
      fileList:[]
    }
  },
  watch: {},
  created() {
    //获取级联选择器里面的商品分类列表
    this.getGoodsList()
  },
  mounted() {},
  methods: {
    async getGoodsList(){
     const {data:res} =await this.$http.get('/categories')
      if(res.meta.status !== 200) return this.$message.error('获取商品列表数据失败')
       this.goodCateList = res.data
    },
    handleChange(){
      //只允许选中三级分类
      if(this.selectKeys.length !== 3){
        return this.selectKeys = []
      }
    },
    //切换标签页,如果没有选择商品分类,就提示要选择一下
    changeTab(activeName, oldActiveName){
          //  oldActiveName要离开的标签页
          //  activeName要去的标签页
      //思路: 判断在第一个标签页,且级联选择有没有选择第三级 
      //      如果没有则返回false , 会阻止标签页的跳转
       if(oldActiveName === '0' && this.addForm.goods_cat.length !== 3){
         this.$message.error('请选择商品分类')
         return false
       }
    },
   async qiehuan(){
            // console.log(this.selectActive);
            //切换标签页时 如果打印的是1 说明选中的是商品参数
            if(this.selectActive === '1'){
            const {data:res} =  await this.$http.get(`categories/${this.fenId}/attributes`,{
                params:{sel:'many'}
               })
               if(res.meta.status !== 200) return this.$message.error('获取商品列表数据失败')
               
               res.data.forEach(v => {
               v.attr_vals = v.attr_vals.length === 0?[] :v.attr_vals.split(' ')
               })
               console.log(res.data);
              this.manyTabList = res.data
              //打印2 说明选中的是商品属性
            }else if(this.selectActive === '2'){
               const {data:res} =  await this.$http.get(`categories/${this.fenId}/attributes`,{
                params:{sel:'only'}
               })
               if(res.meta.status !== 200) return this.$message.error('获取商品列表数据失败')
              this.onlyTabList = res.data
            }
    },
    // 上传组件
      handlePreview(file){
         const trueFile = file.response.data.url
        this.trueFiles = trueFile
        this.dialogVisible = true
      },
      handleRemove(file){
        //1:先获取将要删除的临时路径
         const linshiPath = file.response.data.tmp_path
         this.addForm.pics = this.addForm.pics.filter(v => {
           return v.pic !== linshiPath
         })
      },
      handleSuccess(res){
         const picsList = {pic:res.data.tmp_path}  
         this.addForm.pics.push(picsList)
      },
     add(){
      this.$refs.adRruleForm.validate(async isOk =>{
         if(!isOk) return this.$message.error('表单填写不正确')
         //因为级联选择器要取要数组,这里需要字符串为了各自不干扰,就把数据深拷贝一份
         const from = _.cloneDeep(this.addForm)
         from.goods_cat = from.goods_cat.join(',')
         //动态参数
         this.manyTabList.forEach( v => {
            const manyObj = {
              attr_id:v.attr_id,
              attr_value:v.attr_vals.join(',')
              }
               this.addForm.attrs.push(manyObj)
         })
        
         //静态参数
         this.onlyTabList.forEach( v => {
              const onlyObj = {
                 attr_id:v.attr_id,
                 attr_value:v.attr_vals
              }
              this.addForm.attrs.push(onlyObj)
         })
          from.attrs = this.addForm.attrs
          const {data:res}  = await this.$http.post('/goods',from)
          if(res.meta.status !== 201) return this.$message.error('添加商品失败')
          this.$message.success('添加商品成功')
          this.$router.push('/goods')  
      })
     }
  }
};
</script>
<style scoped lang='less'>
   .el-breadcrumb{
    margin-bottom: 15px;
   }
   .el-alert{
    margin-bottom: 15px;
   }
   .el-tabs{
    margin-top: 20px 
   }
  .btn{
    margin-top: 15px;
  }
</style>